// Package myoffice
// @Author: zhangdi
// @File: word
// @Version: 1.0.0
// @Date: 2023/11/14 17:59
package myoffice

import (
	"fmt"
	"github.com/carmel/gooxml/document"
	"strings"
)

type ReplaceConfig struct {
	PreStr string //占位符号 前 如 {{
	SufStr string //占位符号-后 如 }}
}

func NewReplaceConfig(preStr string, sufStr string) *ReplaceConfig {
	return &ReplaceConfig{PreStr: preStr, SufStr: sufStr}
}

type WordReplace struct {
	doc  *document.Document
	conf *ReplaceConfig
}

// NewWordReplace 模板替换示例
func NewWordReplace(docFilePath string, config *ReplaceConfig) (*WordReplace, error) {
	doc_, err := document.Open(docFilePath)
	if err != nil {
		return nil, err
	}
	if config == nil {
		//传入nil 则初始化，取空值,保证conf不为nil
		config = &ReplaceConfig{}
	}
	return &WordReplace{
		doc:  doc_,
		conf: config,
	}, nil
}

// ReplaceText 遍历段落并替换占位符
// placeholder 占位符
// value 替换的值
func (s *WordReplace) ReplaceText(placeholder string, value string) {
	// 遍历文档中的段落
	for _, p := range s.doc.Paragraphs() {
		for _, r := range p.Runs() {
			tempText := r.Text()
			if strings.Contains(tempText, placeholder) {
				r.ClearContent()
				r.AddText(strings.ReplaceAll(tempText, placeholder, value))
			}
		}
	}
}

// RelaceTableText 遍历变革并替换占位符
// placeholder 占位符
// value 替换的值
func (s *WordReplace) RelaceTableText(placeholder string, value string) {
	// 遍历文档中的表格,表格会单独处理
	for _, t := range s.doc.Tables() {
		for _, r := range t.Rows() {
			for _, c := range r.Cells() {
				// 遍历单元格中的段落
				for _, p := range c.Paragraphs() {
					for _, r := range p.Runs() {
						tempText := r.Text()
						if strings.Contains(tempText, placeholder) {
							r.ClearContent()
							r.AddText(strings.ReplaceAll(tempText, placeholder, value))
						}
					}
				}
			}
		}
	}
}

// ReplaceTexts 替换多个占位符  k是占位符 v是替换后的值
// hasTable 替换的文本是否存在于word表格中
func (s *WordReplace) ReplaceTexts(data map[string]string) {
	for k, v := range data {
		//占位度加上前缀和后缀字符
		placeholder := fmt.Sprintf("%s%s%s", s.conf.PreStr, k, s.conf.SufStr)
		s.ReplaceText(placeholder, v)
	}
}

// ReplaceTextsWhitTable 换多个占位符(替换的文本存在于word的表格中)
// map的 k是占位符 v是替换后的值
func (s *WordReplace) ReplaceTextsWhitTable(data map[string]string) {

	for k, v := range data {
		placeholder := fmt.Sprintf("%s%s%s", s.conf.PreStr, k, s.conf.SufStr)
		s.ReplaceText(placeholder, v)
		s.RelaceTableText(placeholder, v)
	}
}

func (s *WordReplace) SaveToFile(saveFilePath string) error {
	// 保存修改后的文档
	err := s.doc.SaveToFile(saveFilePath)
	if err != nil {
		return err
	}
	return nil
}
